const audio = document.getElementById('audio')
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

const initCvs = () => {
  canvas.width = window.innerWidth * devicePixelRatio;
  canvas.height = (window.innerHeight / 2) * devicePixelRatio;
}
initCvs();

let isInit = false
let dataArr, analyser
audio.onplay = () => {
  if (isInit) {
    return
  }
  const audCtx = new AudioContext() // 创建音频上下文
  const source = audCtx.createMediaElementSource(audio) // 创建音频源节点

  analyser = audCtx.createAnalyser() // 创建分析器节点
  analyser.fftSize = 512 // 快速傅里叶变换 的窗口尺寸
  // 接收分析器节点的分析数据
  dataArr = new Uint8Array(analyser.frequencyBinCount)


  source.connect(analyser) // 音频源节点 与 分析器节点 连接
  analyser.connect(audCtx.destination) // 分析器节点 连接到 输出设备


  isInit = true
}

const draw = () => {
  requestAnimationFrame(draw)
  // 清空画布
  const { width, height } = canvas
  ctx.clearRect(0, 0, width, height)

  if (!isInit) {
    return
  }

  // 获取每帧的音频数据
  analyser.getByteFrequencyData(dataArr)
  const arrlen = dataArr.length
  const barWidth = width / arrlen
  ctx.fillStyle = 'green'
  for (let i = 0; i < arrlen; i++) {
    const data = dataArr[i] // 8 bit
    const barHeight = (data / 255) * height
    const x = i * barWidth
    const y = height - barHeight
    ctx.fillRect(x, y, barWidth - 2, barHeight)
  }
}
draw()